const express = require('express');
const { DB } = require('../utils/db.js')
const router = express.Router();
const config = require('../config/index.js')
const {upload} = require('../utils/upload.js');
const uploadRoute = require('./uploadFile.js');

// 定义一个简单的路由
router.get('/user', (req, res) => {
 res.send('common user info');
});
// 定义一个简单的路由
router.post('/upload',upload.single('file'), async (req, res) => {
 // upload.single('file') 处理单个文件的上传，并将文件信息存储在 req.file 中
 // 'file' 即form-data 表单的formData.append的key值 

 // 获取上传后的文件完整路径
  // const filePath = path.join(path.resolve(__dirname, '../public/'), req.file.filename)
  // 拼接完整的文件路径 服务器地址（若是设置静态托管地址，以托管地址设置）+文件名
  const filePath = config.host+'/'+req.file.filename
  let formData = {
    file: filePath,
    ...req.body
  }
  const db = await DB('hello');
  res.send({
   message: 'File uploaded successfully.',
   data: formData
  });
  await db.insert('uploadInfo', formData)
});


// 定义一个简单的路由
router.post('/m-upload',upload.array('photos',5), async (req, res) => {
 let filePath = ""
 for (const m of req.files) {
  filePath += config.host+'/'+m.filename.slice(-20)+";"
 }
  let formData = {
    file: filePath,
    ...req.body
  }
  res.send({
   message: 'File uploaded successfully.',
   data: formData
  });
  const db = await DB('hello');
  await db.insert('uploadInfo', formData)
});


// form-data 表单中可以有多个文件  有多少个form-data的key，数组就有多个
let array = [{name:'photos',maxCount:5},{name:'multer',maxCount:5}]
router.post('/max-upload',upload.fields(array), async (req, res) => {
 let filePath = ""
 for (const key in req.files) {
  for (const m of req.files[key]) {
   filePath += config.host+'/'+m.filename.slice(-20)+";"
  }
 }
  let formData = {
    file: filePath,
    ...req.body
  }
  res.send({
   message: 'File uploaded successfully.',
   data: formData
  });
  const db = await DB('hello');
  await db.insert('uploadInfo', formData)
});

// 单独的处理form-data 表单  不处理文件
router.post('/form-upload',upload.none(), async (req, res) => {
 let filePath = ""
  let formData = {
    file: filePath,
    ...req.body
  }
  res.send({
   message: 'save formData successfully.',
   data: formData
  });
  const db = await DB('hello');
  await db.insert('uploadInfo', formData)
});

// 可以定义更多 "/common/xxx" 的路由...
router.use('/',uploadRoute)

// 可以定义更多的路由...

module.exports = router;